<template>
    <div style="width: 95%;margin: auto;">
        <el-form :inline="true" :model="carForm" class="demo-form-inline">
            <el-form-item style="width: 180px;">
                <el-input v-model="carForm.carname" placeholder="请输入汽车名称" clearable />
            </el-form-item>
            <el-form-item style="width: 180px;">
                <el-select v-model="carForm.ctid" placeholder="请选择汽车类型" clearable style="width: 200px;">
                    <el-option label="轿车" value="1" />
                    <el-option label="SUV" value="2" />
                    <el-option label="跑车" value="3" />
                    <el-option label="旅行车" value="4" />
                    <el-option label="越野车" value="5" />
                    <el-option label="小型车" value="6" />
                    <el-option label="MPV" value="7" />
                </el-select>
            </el-form-item>
            <el-form-item style="width: 180px;">
                <el-input v-model="carForm.brandname" placeholder="请输入汽车品牌" clearable />
            </el-form-item>
            <el-form-item style="width: 180px;">
                <el-input v-model="carForm.plate" placeholder="请输入汽车车牌号" clearable />
            </el-form-item>
            <el-form-item style="width: 180px;">
                <el-input v-model="carForm.price" placeholder="请输入汽车日租金额" clearable />
            </el-form-item>
            <el-form-item style="width: 180px;">
                <el-button type="primary" @click="findAll(1)">查询</el-button>
                <el-button @click="resetForm()">重置</el-button>
            </el-form-item>
        </el-form>
    </div>

    <!-- 新增和修改对话框 -->
    <div style="width: 95%;margin: auto;">
        <el-button type="primary" @click="showDialog()" :icon="Plus"> 新增</el-button>
        <el-button type="primary" @click="batchedDeleteByIds()" :icon="Delete"> 批量删除</el-button>
    </div>
    <div>
        <!-- 新增用户和修改对话框 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="25%" draggable :show-close="false"
            :close-on-click-modal="false" :close-on-press-escape="false">
            <!-- 新增用户表单 -->
            <el-form :inline="true" :model="dialog.car" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="dialog.car.carname" placeholder="请输入汽车名" clearable
                        style="width: 200px;height: 35px;" />
                </el-form-item>
                <!-- 显示上传图片 -->
                <div
                    style="position:  absolute;top: 50px;left: 240px; width: 30%; height: 100px;background-color:#FAFAFA ;text-align: center;border-radius: 5px;">
                    <el-image @click="showUploadImageDialog()" :src="dialog.car.imgpath"
                        style="border-radius: 5%;width: 100%;" />
                </div>

                <el-select v-model="dialog.car.ctid" placeholder="选择汽车类型" clearable style="width: 200px;">
                    <!-- label：表示显示文本内容  value:表示提交值 -->
                    <el-option label="轿车" :value="1" />
                    <el-option label="SUV" :value="2" />
                    <el-option label="跑车" :value="3" />
                    <el-option label="旅行车" :value="4" />
                    <el-option label="越野车" :value="5" />
                    <el-option label="小型车" :value="6" />
                    <el-option label="MPV" :value="7" />
                </el-select>
                <el-input v-model="dialog.car.brandname" :rows="2" placeholder="输入品牌名"
                    style="width: 340px;margin-top: 20px;" />
                <el-input v-model="dialog.car.plate" :rows="2" placeholder="输入车牌号"
                    style="width: 340px;margin-top: 20px;" />
                <el-input v-model="dialog.car.price" :rows="2" placeholder="输入日租金额"
                    style="width: 340px;margin-top: 20px;" />
                <el-input v-model="dialog.car.productYear" :rows="2" placeholder="输入生产年份"
                    style="width: 340px;margin-top: 20px;" />
                <el-input v-model="dialog.car.level" :rows="2" placeholder="输入汽车等级"
                    style="width: 340px;margin-top: 20px;" />
                <el-select v-model="dialog.car.eid" placeholder="选择能源类型" style="width: 340px;margin-top: 20px;">
                    <el-option label="燃油车" :value="1" />
                    <el-option label="纯电动车" :value="2" />
                    <el-option label="混合动力车" :value="3" />
                </el-select>
                <el-input v-model="dialog.car.displacement" :rows="2" placeholder="输入排放量"
                    style="width: 340px;margin-top: 20px;" />
                <el-select v-model="dialog.car.gid" placeholder="选择档位类型" style="width: 340px;margin-top: 20px;">
                    <el-option label="自动" :value="1" />
                    <el-option label="手动" :value="2" />
                    <el-option label="手自一体" :value="3" />
                    <el-option label="固定齿比变速箱" :value="4" />
                    <el-option label="双离合" :value="5" />
                    <el-option label="多级全混动变速箱" :value="6" />
                    <el-option label="电子无极变速" :value="7" />
                    <el-option label="多档双离合" :value="8" />
                </el-select>
                <el-form-item style="margin-top: 20px;">
                    <el-button type="primary" @click="insertAndUpdateCar">{{ dialog.btnText }}</el-button>
                    <el-button type="primary" @click="clearFormData">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>

    <div>
        <!-- 新增用户和修改对话框 -->
        <el-dialog v-model="uploadDialog.visible" title="文件上传" width="30%" draggable>
            <el-upload :action="uploadDialog.uploadUrl" list-type="picture-card" :file-list="fileList"
                :limit="uploadDialog.limit" :auto-upload="uploadDialog.autoUpload" :on-change="handlerImage">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
            <!-- 添加上传按钮 -->
            <el-form-item style="margin-top: 10px;margin-left: 320px;">
                <el-button type="primary" @click="uploadHandler()">上传</el-button>
            </el-form-item>
        </el-dialog>
    </div>
    <br>
    <!-- 所有用户信息展示 -->
    <el-table :data="carPage.cars" style="width: 95% ; margin:auto" @selection-change="handleSelectionChange">
        <!-- 添加复选框选项 -->
        <el-table-column type="selection" width="55" />
        <el-table-column fixed prop="carid" label="编号" width="80" />
        <el-table-column prop="carname" label="姓名" width="300" />
        <el-table-column prop="ctname" label="类型" width="80">
            <!-- <template #default="scope">
                <div v-for="(ctid, index) in scope.row.ctid">
                    <el-tag v-if="ctid == 1" type="primary">轿车</el-tag>
                    <el-tag v-else-if="ctid == 2" type="danger">SUV</el-tag>
                    <el-tag v-else-if="role.rname == 'vip用户'" type="success">{{ role.rname }}</el-tag>
                    <el-tag v-else type="info">{{ role.rname }}</el-tag>
                </div>
            </template> -->
        </el-table-column>
        <el-table-column prop="brandname" label="品牌" width="80" />
        <el-table-column prop="plate" label="车牌号" width="200" />
        <el-table-column label="汽车照片" prop="imgpath" width="150px">
            <!-- 插槽 -->
            <template #default="scope">
                <!-- <el-image style="width: 80px;border-radius: 5%;":src="scope.row.imgPath"/> -->
                <el-avatar shape="circle" :size="50" :src="scope.row.imgpath" />
            </template>
        </el-table-column>
        <el-table-column prop="price" label="日租金额" width="200" />
        <el-table-column label="操作" min-width="160" fixed="right">
            <template #default="scope">
                <el-button link type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">
                    修改
                </el-button>
                <el-button link type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>


    <!-- 分页标签 -->
    <div style="width: 95%;margin: 10px auto;">
        <el-pagination background layout="prev, pager, next" v-model:page-size="carForm.pageSize"
            v-model:current-page="carForm.pageNum" :total="carForm.total" @current-change="findAll" />
    </div>
</template>
<script lang="ts" setup>

import { ref, reactive, onMounted } from 'vue'
import { Delete, Edit, Female, Male, HomeFilled, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'


const carPage = reactive({
    cars: [],//存放后端查询用户数据变量
})

//声明一个对象用于条件查询
let carForm = ref({
    pageNum: 0,
    pageSize: 7,
    total: 0,
})
//根据条件查询信息
const findAll = async (currentpage) => {
    carForm.value.pageNum = currentpage;
    let r = await request.post("/car/queryCondition", carForm.value);
    if (r.data.success) {
        carPage.cars = r.data.data.list;
        carForm.value.pageNum = r.data.data.pageNum;
        carForm.value.pageSize = r.data.data.pageSize;
        carForm.value.total = r.data.data.total;
    }
    console.log(carPage.cars);

}
onMounted(() => {
    findAll(1);
});
//定义对话框属性
const dialog = ref({
    visible: false,
    title: '',
    btnText: '',
    car: {},
})
//定义变量控制文件上传
const uploadDialog = reactive({
    visible: false, //隐藏对话框
    uploadUrl: "",
    fileList: [], //保存所有上传文件集合
    limit: 1,//控制文件上传个数
    autoUpload: false,
    uploadFile: null as File | null,
})

//实现用户新增或者修改操作
const insertAndUpdateCar = async () => {
    if (dialog.value.btnText == "新增") {
        //查看是否有值
        //发送请求实现熊增用户功能
        let res = await request.post("/car/insert", dialog.value.car);
        //判断是否新增成功
        if (res.data.success) {
            //1.清空表单
            clearFormObj();
            //2.刷新页面
            findAll(1);
            //3.显示提示信息
            ElMessage.success("添加成功")
            //4.关闭对话框
            dialog.value.visible = false;
        } else {
            ElMessage.error("添加失败:没有此品牌");
            dialog.value.visible = false;
        }
    } else {//表示修改
        //1.获取数据发送请求实现修改用户信息
        let res = await request.put("/car/update", dialog.value.car);
        //判断是否新增成功
        if (res.data.success) {
            //1.清空表单
            clearFormObj();
            //2.刷新页面
            findAll(carForm.value.pageNum);//查询当前页
            //3.显示提示信息
            ElMessage.success("修改成功")
            //4.关闭对话框
            dialog.value.visible = false;
        }
    }
}

//显示文件上传对话框
const showUploadImageDialog = () => {
    uploadDialog.visible = true;
}

//显示修改用户对话框
const handleEdit = (index, row) => {
    //显示表单信息
    dialog.value.car = row;
    //设置对话框标题
    dialog.value.title = "修改骑车";
    //设置按钮文本内容
    dialog.value.btnText = "更新数据";
    //显示对话框
    dialog.value.visible = true;
}

//显示新增对话框
const showDialog = () => {
    //1.设置对话框标题
    dialog.value.title = "新增汽车";
    //2.设置对话框 案例文本
    dialog.value.btnText = "新增";
    //3.清空表单
    clearFormObj();
    //4.显示对话框
    dialog.value.visible = true;
}

//选中文件时触发函数
const handlerImage = (file) => {
    uploadDialog.uploadFile = file.raw;
}
const clearFormData = () => {
    dialog.value.visible = false; // 关闭对话框
    findAll(carForm.value.pageNum);
}
const resetForm = (() => {
    carForm.value.carname = "";
    carForm.value.ctid = null;
    carForm.value.brandname = "";
    carForm.value.plate = "";
    carForm.value.price = "";
})
//清空表单函数
const clearFormObj = () => {
    dialog.value.car.carname = '';
    dialog.value.car.ctid = 1;
    dialog.value.car.brandname = '';
    dialog.value.car.imgpath = 'http://localhost:80/carid1.png';
    dialog.value.car.plate = '';
    dialog.value.car.price = null;
}
//实现文件上传函数
const uploadHandler = async () => {

    //文件上传详细步骤
    //1.创建FormData对象
    let formData = new FormData();
    //2.设置上传对象对象
    formData.append("file", uploadDialog.uploadFile)
    //3.设置上传类型
    let contentType = { "ContentType": "multipart/form-data" }
    formData.append("headers", contentType);
    //4.发送请求实现文件上传
    let res = await request.post("/car/fileUpload", formData);
    if (res.data.success) {
        //把上传文件保存到表单imgPath中
        dialog.value.car.imgpath = res.data.data; //http://localhost:80/xxxx.png
        //显示提示信息
        ElMessage.success("上传成功");
        //关闭文件上传对话框
        uploadDialog.visible = false;
    }
}






//删除行操作
const handleDelete = async (row) => {
    let res = await request.delete(`/car/deleteById/${row.carid}`, { params: row });
    if (res.data.success) {
        ElMessage.success("删除成功");
        findAll(1);
    }
}
// 批量删除
//定义数组，存放批量删除元素集合
const cars = reactive({
    usersIds: [],
})
//复选框被选择触发函数
const handleSelectionChange = (rows) => {
    cars.usersIds = rows;
}
const batchedDeleteByIds = async () => {
    //1.判断数组中是否包含删除元素
    if (cars.usersIds.length <= 0) {
        ElMessage.warning("请选择删除项...")
        return; //结束
    }
    let ids = [];
    //2.遍历数组，获取所有id值
    for (let i = 0; i < cars.usersIds.length; i++) {
        let u = cars.usersIds[i];
        //把值添加到数组中
        ids.push(u.carid);
    }
    const idsStr = ids.toString();
    //3.发送异步请求
    let response = await request.delete(`/car/deleteByIds/${ids}`, { params: { idsStr } });
    if (response.data.success) {
        //显示提示信息
        ElMessage.success("批量删除成功")
        //刷新页面
        findAll(1);
    }
}
</script>